﻿using System;
using System.Net.Sockets;
using System.Text;

namespace VirtualKeyboard.Service.TcpServices
{
    internal static class AnalyseHelper
    {
        private const int MagicNumber = 0xB4B4B4;
        private const int ActionSize = 32;
        private static readonly byte[] MagicNumberBuffer = BitConverter.GetBytes(MagicNumber);

        public static TcpRequest Analyse(byte[] buffer, int offset, int length)
        {
            int _offset = offset;
            if (length < 8)
            {
                return null;
            }
            var request =new TcpRequest();
            int size = BitConverter.ToInt32(buffer, _offset);
            request.Length = size;
            _offset += 4;
            request.Action = Encoding.UTF8.GetString(buffer, _offset, ActionSize).TrimEnd('\0');
            _offset += ActionSize;
            request.Context = Encoding.UTF8.GetString(buffer, _offset, size);

            return request;
        }

        public static int SetBuffer(SocketAsyncEventArgs eventArgs,TcpResponse response)
        {
            if (string.IsNullOrWhiteSpace(response.Context)) return 0;

            byte[] contextBuffer = Encoding.UTF8.GetBytes(response.Context);

            
            var buffer = eventArgs.Buffer;
            var offset = eventArgs.Offset;
            var sizeBuffer = BitConverter.GetBytes(contextBuffer.Length);
            Array.Copy(sizeBuffer, 0, buffer, offset, 4);
            offset += 4;
            var stateCodeBuffer = BitConverter.GetBytes(response.StateCode);
            Array.Copy(stateCodeBuffer, 0, buffer, offset, 4);
            offset += 4;
            Array.Copy(contextBuffer, 0, buffer, offset, contextBuffer.Length);
            return contextBuffer.Length + 8;
        }
    }
}
